<template>
	<div style="height: calc(100%);overflow: auto;padding: 0 20px">
		<!--    <el-button type="primary" @click="showAddQualityDialog">新建质检</el-button>-->
		<div class="pageTableMenuView">
			<div class="pageTableTitle">
				<div>首件检</div>
				<el-switch v-model="switchData.shoujian" active-text="启用" style="margin-left: 10px" @change="isSwitchChange()" />
			</div>
			<div class="pageTableButView">
				<el-button @click="showAddQualityDialog" type="primary" :icon="Plus">新建</el-button>
			</div>
		</div>
		<el-table :data="baseData1" style="width: 100%">
			<el-table-column type="index" width="80" label="序号" align="center" />
			<el-table-column prop="quality" label="质检名称" align="center"></el-table-column>
			<el-table-column prop="qualityType" label="质检类型" align="center"></el-table-column>
			<el-table-column label="操作" width="150" align="center">
				<template #default="scope">
					<el-button type="text" @click="editQuality(scope.row)">编辑</el-button>
					<el-button text @click="deleteQuality(scope.row)" type="danger">删除</el-button>
				</template>
			</el-table-column>
		</el-table>
		<div class="pageTableMenuView">
			<div class="pageTableTitle">
				<div>末件检</div>
				<el-switch v-model="switchData.mojian" active-text="启用" style="margin-left: 10px" @change="isSwitchChange()" />
			</div>
			<div class="pageTableButView">
				<!--        <el-button @click="showAddQualityDialog" type="primary" :icon="Plus">新建</el-button>-->
			</div>
		</div>
		<el-table :data="baseData2" style="width: 100%">
			<el-table-column type="index" width="80" label="序号" align="center" />
			<el-table-column prop="quality" label="质检名称" align="center"></el-table-column>
			<el-table-column prop="qualityType" label="质检类型" align="center"></el-table-column>
			<el-table-column label="操作" width="150" align="center">
				<template #default="scope">
					<el-button type="text" @click="editQuality(scope.row)">编辑</el-button>
					<el-button text @click="deleteQuality(scope.row)" type="danger">删除</el-button>
				</template>
			</el-table-column>
		</el-table>
		<div class="pageTableMenuView">
			<div class="pageTableTitle">
				<div>工序完工检</div>
				<el-switch v-model="switchData.shengchan" active-text="启用" style="margin-left: 10px" @change="isSwitchChange()" />
			</div>
			<div class="pageTableButView">
				<!--        <el-button @click="showAddQualityDialog" type="primary" :icon="Plus">新建</el-button>-->
			</div>
		</div>
		<el-table :data="baseData3" style="width: 100%">
			<el-table-column type="index" width="80" label="序号" align="center" />
			<el-table-column prop="quality" label="质检名称" align="center"></el-table-column>
			<el-table-column prop="qualityType" label="质检类型" align="center"></el-table-column>
			<el-table-column label="操作" width="150" align="center">
				<template #default="scope">
					<el-button type="text" @click="editQuality(scope.row)">编辑</el-button>
					<el-button text @click="deleteQuality(scope.row)" type="danger">删除</el-button>
				</template>
			</el-table-column>
		</el-table>
		<div class="pageTableMenuView">
			<div class="pageTableTitle">
				<div>巡检</div>
				<el-switch v-model="switchData.xunjian" active-text="启用" style="margin-left: 10px" @change="isSwitchChange()" />
			</div>
			<div class="pageTableButView">
				<!--        <el-button @click="showAddQualityDialog" type="primary" :icon="Plus">新建</el-button>-->
			</div>
		</div>
		<el-table :data="baseData4" style="width: 100%">
			<el-table-column type="index" width="80" label="序号" align="center" />
			<el-table-column prop="quality" label="质检名称" align="center"></el-table-column>
			<el-table-column prop="qualityType" label="质检类型" align="center"></el-table-column>
			<el-table-column label="操作" width="150" align="center">
				<template #default="scope">
					<el-button type="text" @click="editQuality(scope.row)">编辑</el-button>
					<el-button text @click="deleteQuality(scope.row)" type="danger">删除</el-button>
				</template>
			</el-table-column>
		</el-table>
		<!-- 新建质检弹窗 -->
		<el-dialog title="新建质检" v-model="data.showQualityDialog">
			<el-form :model="data.newQuality" label-width="100px" ref="qualityFormRef" :rules="qualityRules">
				<el-row>
					<el-col :span="12">
						<el-form-item label="质检类型" prop="qualityType">
							<el-select v-model="data.newQuality.qualityType" placeholder="请选择质检类型" style="width: 100%"
												 @change="typeChange">
								<el-option v-for="option in qualityTypes" :key="option.value" :label="option.label"
													 :value="option.value"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
				<el-table :data="data.newQuality.keys" stripe style="width: 100%" height="300px">
					<el-table-column type="index" label="序号" width="80" align="center"></el-table-column>
					<el-table-column label="质检项" align="center">
						<template #default="scope">
							<!-- <el-input v-model="scope.row.value" placeholder="请输入质检项" style="width: 100%" /> -->
							<el-select v-model="scope.row.value" placeholder="" clearable filterable
												 @change="qualityPlanChange(scope.$index)">
								<el-option v-for="item in qualityPlanList" :key="item.id" :label="item.name"
													 :value="item.name"></el-option>
							</el-select>
						</template>
					</el-table-column>
					<el-table-column prop="address" label="Address" width="150" align="center">
						<template #header>
							<el-button :icon="Plus" text @click="handleAdd">新建</el-button>
						</template>
						<template #default="scope">
							<el-button :icon="Delete" type="danger" text
												 @click="handleRemove(scope.$index)">删除
							</el-button>
						</template>
					</el-table-column>
				</el-table>
			</el-form>
			<template #footer>
				<el-button @click="data.showQualityDialog = false">取消</el-button>
				<el-button type="primary" @click="addQuality">确定</el-button>
			</template>
		</el-dialog>
	</div>
</template>
<script setup>
import axiosInstance from '@/utils/http/api';
import { reactive, ref, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Delete, Plus } from '@element-plus/icons-vue';

const data = reactive({
	showQualityDialog: false,
	newQuality: { quality: '', qualityType: '', keys: [{ value: '' }] },
	deviceOptions: []

});
const baseData = ref([]);
const indexParenId = ref();
const qualityTypes = [
	{ value: '首件检', label: '首件检', num: '1' },
	{ value: '末件检', label: '末件检', num: '2' },
	{ value: '生产检', label: '工序完工检', num: '3' },
	{ value: '巡检', label: '巡检', num: '4' }
];
const qualityPlanList = ref([]);
const props = defineProps({
	devicesData: Array,
	onSubmit: Function
});

const typeChange = (e, i) => {
	if (!i) {
		data.newQuality.keys = [{}];
	}
	for (const item of qualityTypes) {
		if (e == item.value) {
			axiosInstance.post('/api/basedataQualityScheme/getPage', {
				current: 1,
				pageSize: 999999,
				qualityType: item.num
			})
				.then(res => {
					qualityPlanList.value = res.data.records;
				});
		}
	}
};

const qualityFormRef = ref(null);
const qualityRules = {
	qualityType: [{ required: true, message: '请选择质检类型', trigger: 'change' }]
};

const qualityPlanChange = (e) => {
	const loop = JSON.parse(JSON.stringify(data.newQuality.keys));
	const label = loop[e].value;
	let count = 0;
	for (const item of loop) {
		if (item.value == label) {
			count++;
		}
	}
	if (count > 1) {
		ElMessage.error('不能重复添加');
		data.newQuality.keys[e].value = '';
		return false;
	}

	for (const item of qualityPlanList.value) {
		if (item.name == data.newQuality.keys[e].value) {
			data.newQuality.keys[e].qrId = item.id;
			data.newQuality.keys[e].qualityJson = item.qualityJson;
		}
	}
};

const baseData1 = ref([]);
const baseData2 = ref([]);
const baseData3 = ref([]);
const baseData4 = ref([]);

watch(props, (val) => {
	if (val.devicesData) {
    console.log(val.devicesData,'devicesDatadevicesData')
    switchData.value = val.devicesData.switchData || {}
		baseData.value = val.devicesData.quality;
		indexParenId.value = val.devicesData.index;
		baseData1.value = [];
		baseData2.value = [];
		baseData3.value = [];
		baseData4.value = [];
		if (baseData.value)
			for (const item of baseData.value) {
				if (item.qualityType == '首件检') {
					baseData1.value.push(item);
				}
				if (item.qualityType == '末件检') {
					baseData2.value.push(item);
				}
				if (item.qualityType == '生产检') {
					baseData3.value.push(item);
				}
				if (item.qualityType == '巡检') {
					baseData4.value.push(item);
				}
			}
	} else {
		baseData1.value = [];
		baseData2.value = [];
		baseData3.value = [];
		baseData4.value = [];
	}
});

const showAddQualityDialog = () => {
	data.showQualityDialog = true;
	data.newQuality = { quality: '', qualityType: '', keys: [{ value: '' }] };
};

const getDeviceOptions = async () => {
	try {
		const response = await axiosInstance.post('/api/basedataEquipment/getAll', {});
		data.deviceOptions = response.data;
	} catch (error) {
		console.error('获取质检选项失败:', error);
	}
};

const handleAdd = () => {
	data.newQuality.keys.push({ value: '' });
};

const handleRemove = (index) => {
	data.newQuality.keys.splice(index, 1);
};

const addQuality = () => {
	qualityFormRef.value.validate((valid) => {
		if (valid) {
			let addData = [];
			if (!data.newQuality.keys || data.newQuality.keys.length == 0) {
				ElMessage.error('请添加质检项');
				return false;
			}
			for (const item of data.newQuality.keys) {
				if (!item.value) {
					ElMessage.error('请输入质检项');
					return false;
				}
			}
			if (data.newQuality.index_id) {
				addData = replaceItemById(baseData?.value, data.newQuality);
			} else {
				const ids = Math.floor(Math.random() * 100);
				if (baseData.value) {
					addData = [...baseData?.value, { ...data.newQuality, index_id: ids }];
				} else {
					addData = [{ ...data.newQuality, index_id: ids }];
				}
			}

			if (props.onSubmit) {
				for (const item of addData) {
					item.quality = item.keys[0].value;
					item.qrId = item.keys[0].qrId;
					item.qualityJson = item.keys[0].qualityJson;
					console.log(qualityTypeEnum.value.find(items => items.label == item.qualityType));
					item.qualityTypeStatus = qualityTypeEnum.value.find(items => items.label == item.qualityType).value;
				}
				console.log(addData, ' addDataaddDataaddData');
				props.onSubmit(addData, 'quality', indexParenId.value);
			}
			data.showQualityDialog = false;
		}
	});
};

const switchData = ref({});

const isSwitchChange = () => {
	console.log(switchData.value, 'czq');
	props.onSubmit(switchData.value, 'switchData', indexParenId.value);
};

const qualityTypeEnum = ref([
	{
		label: '首件检',
		value: '1'
	},
	{
		label: '末件检',
		value: '2'
	},
	{
		label: '生产检',
		value: '3'
	},
	{
		label: '巡检',
		value: '4'
	}
]);

const editQuality = (row) => {
	data.newQuality = row;
	typeChange(row.qualityType, true);
	data.showQualityDialog = true;
};

const deleteQuality = (row) => {
	ElMessageBox.confirm('确定删除该条记录吗？', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	}).then(async () => {
		const delBaseData = baseData?.value.filter(i => i.index_id !== row.index_id);
		if (props.onSubmit) {
			props.onSubmit(delBaseData, 'quality', indexParenId.value);
		}
	}).catch(() => {
	});
};

const replaceItemById = (items, newItem) => {
	return items.map(i => {
		if (i.index_id === newItem.index_id) {
			return newItem;
		}
		return i;
	});
};

// onMounted(() => {
//   getDeviceOptions();
// });
</script>
<style scoped>
.el-table {
	margin-top: 20px;
}

.pageTableMenuView {
	margin-top: 25px;
}

.pageTableMenuView:first-of-type {
	margin-top: 0;
}
</style>
